<template>
    <view class="index-page">
      <uni-navbar 
        title="任务详情" 
        :border="false"
        :fixed="true"
        :height="barHeight"
        :rightWidth="60"
        :leftWidth="60"
        titleStyle="color:#fff;fontSize:18px;"
        :bgColor="isWhiteAppBar ? '#FF5500' : 'transparent'"
        :placeholder="false"
        :autoBack="true"
       
      > 
        <view slot="left">
          <image v-if="!isMpAlipay && !isMpBaidu && !isMpToutiao" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;"></image>
        </view>
      </uni-navbar>
  
      <scroll-view
        class="box-1"
        :scroll-y="true"
        :refresher-enabled="false"
        :style="{paddingTop: headHt}"
        refresher-background="#ffffff"
        @scroll="scrollEv"
        >
        <view class="fg-white box-type"> 
            <image class="img-type" :src="staticHost + '/wf_type.png'" mode="widthFix"></image>
            <view style="margin-left: 16rpx;"> 
                <view class="text-bold">{{taskTitle}}</view>
                <view class="text-2">{{repeateDes}}</view>
             </view>
        </view>
        <view class="fg-white" style="padding: 32rpx" v-if="remarker"> 
             <view class="text-bold">任务说明</view>
             <view class="text-2">{{remarker}}</view>
        </view>
        <view class="fg-white" style="padding: 32rpx;"> 
            <view class="text-bold">任务详情</view>
          
            <!-- 1二维码 2链接 3说明图 4邀请码 5验证图 6验证文字 -->

            <view style="width: 100%;" v-for="(stepItem,index) in stepList" :key='index'>
                <!-- 二维码 -->
            <view class="step-box" v-if="stepItem.dtype == 1"> 
                    <text class="text-number">{{index+1}}</text>
                    <view class="step-ly"> 
                        <view class="step-title"> {{stepItem.title}}</view>
                        <image class="img-qcode" :src="stepItem.picUrl" mode="widthFix" @tap ="previewImg(stepItem.picUrl)"></image>
                        <view style="display: flex;margin-top: 24rpx;">
                            <text class="dark-btn" v-if="isH5" @tap="qrCodeScan(stepItem.picUrl)">识别二维码</text>
                            <text class="dark-btn" @tap="saveImg(stepItem.picUrl)">保存扫码</text>
                        </view>
                    </view>
                </view>
                <!-- 链接 -->
              <view class="step-box" v-else-if="stepItem.dtype == 2" > 
                 <text class="text-number">{{index+1}}</text>
                 <view class="step-ly"> 
                    <view class="step-title"> {{stepItem.title}}</view>
                    <view style="display: flex;margin-top: 24rpx;">
                        <text class="dark-btn" v-if="isH5" @tap ="openLink(stepItem.value)">打开链接</text>
                        <text class="dark-btn" @tap ="copyTxt(stepItem.value)">复制链接</text>
                    </view>
                 </view>
               </view>
               <!-- 说明图 -->
               <view class="step-box" v-else-if="stepItem.dtype == 3"> 
                    <text class="text-number">{{index+1}}</text>
                    <view class="step-ly"> 
                        <view class="step-title"> {{stepItem.title}}</view>
                        <view style="width: 100%;margin-top: 24rpx; position: relative;">
                            <view class="text-img-des">说明图</view>
                            <image class="img-des" :src="stepItem.picUrl" mode="widthFix" @tap ="previewImg(stepItem.picUrl)"></image>
                        </view>
                    </view>
                </view>
               
                <!-- 邀请码 -->
               <view class="step-box" v-else-if="stepItem.dtype == 4"> 
                    <text class="text-number">{{index+1}}</text>
                    <view class="step-ly"> 
                        <view class="step-title"> {{stepItem.title}}</view>
                        <view style="width: 100%; display: flex;margin-top: 24rpx;">
                            <view class="text-invite">{{stepItem.value}}</view>
                            <text class="dark-btn" @tap ="copyTxt(stepItem.value)">复制</text>
                        </view>
                    </view>
                </view>

                
                <!-- 验证图 -->
               <view class="step-box" v-else-if="stepItem.dtype == 5"> 
                    <text class="text-number">{{index+1}}</text>
                    <view class="step-ly"> 
                        <view class="step-title"> {{stepItem.title}}</view>
                        <view style="width: 100%; display: flex;margin-top: 24rpx;">
                            <view style="flex: 1; position: relative;">
                                <view class="text-img-des">验证图</view>
                                <image :class="[isEdit? 'img-check' : 'img-des' ]" :src="stepItem.picUrl" mode="widthFix" @tap ="previewImg(stepItem.picUrl)"></image>
                            </view>
                            <view style="width: 20rpx;"></view>
                            <view  style="flex: 1; background-color: #F4F5F6; text-align: center;  position: relative; " v-if="isEdit">
                                <view style="height: 100%;width: 100%; position: absolute; z-index: 99;"  v-if="stepItem.upLoadImg"> 
                                    <image  style="height: 100%; width: 100%; " 
                                    :src="stepItem.upLoadImg" mode="widthFix" @tap ="previewImg(stepItem.upLoadImg)">
                                    </image>
                                </view>
                                <image style=" height: 40rpx; width: 40rpx;position: absolute; z-index: 199; right: 0;"
                                  :src="staticHost + '/wf_close.png'" @tap="cleanImg(index,stepItem)" v-if="stepItem.upLoadImg">
                                </image>
                                <view v-if="!stepItem.upLoadImg" style="height: 100%; display: flex;flex-direction: column;align-items: center;justify-content: center;" @tap="selUpImg(index,stepItem)"> 
                                    <view>
                                        <image :src="staticHost + '/wf_add_photo.png'" mode="widthFix" style="width:40rpx;height:40rpx;"></image>
                                        <view style="color: #7B828E; margin-top: 24rpx;font-size: 24rpx;">添加照片</view>
                                    </view>
                                </view>
                                

                            </view>
                        </view>
                    </view>
                </view>

                <!-- 验证文字 -->
               <view class="step-box" v-else-if="stepItem.dtype == 6"> 
                    <text class="text-number">{{index+1}}</text>
                    <view class="step-ly"> 
                        <view class="step-title"> {{stepItem.title}}</view>
                        <view style="width: 100%; display: flex;margin-top: 24rpx;">
                            <view class="input-item" v-if="isEdit"> 
                                <input class="input-value"  placeholder-style="color:#AEB4BE;font-size: 28rpx;"  placeholder="请按要求输入内容" v-model="stepItem.value" />                           
                            </view>
                            <view  class="text-input-tip" v-else > 
                                请按要求输入内容
                            </view>
                        </view>
                    </view>
                </view>

            </view>
            
        </view>
        <view style="height: 40rpx;"></view>
      </scroll-view>
      <view class="pg-bottom">
            <view class="btn-light" @tap ="toGiveUp()" v-if="subStatus == 0">放弃</view>
            <view class="btn-light" @tap ="applyTask()" v-if="subStatus == 100">重新报名</view>
            <view class="btn" @tap="dealCommitTask" v-if="subStatus == 0 || subStatus == 3">提交验证</view>
            <view class="btn" @tap="applyTask()" v-if="subStatus != 0 && subStatus != 1 && subStatus != 2 && subStatus != 3 &&  subStatus != 100">立即报名</view>
            <view :class="['btn','disable']"  v-if="subStatus == 100 || subStatus == 1 || subStatus == 2">{{getBtnText()}}</view>
      </view> 

      <WfCommonPop v-if="isViewGiveup" v-model="isViewGiveup" 
        :config="{title:'温馨提示', cancelBtnTxt:'取消', 
        content:'是否确认放弃此签到任务，放弃后完成签到需要报名其他任务。', 
        btnTxt: '确认放弃', 
        isConfirm: true,
        position: 'left'
        }"
        @okEv="saveGiveUp"
      >
        </WfCommonPop>
    </view>
 </template>  
 <script>
 import { staticHost } from '@/setting';
 import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'
 import { setPreviewData } from '@/utils/util'

 import {queryTaskDetail,taskApply,giveUpTask ,submitTask} from '@/pages/welfare/api/index';
 import native from '@/static/js/nativeApp';
 import WfCommonPop from '@/pages/welfare/components/WfCommonPop'
 import { isH5, isMpAlipay, isMpBaidu, isMpToutiao, isMpKuaishou } from '@/utils/platform';
 import { copy, saveAlbum, pickAndUploadImage } from '@/utils/index'
import { uploadExec } from '@/utils/uploadAliyun'

 export default {
    mixins: [ statusBarInfo ],
    components: {
        WfCommonPop
    },
    data(){
       return{
            isMpWeixinH5: false,
            staticHost,
            isMpAlipay,
            isMpBaidu,
            isMpToutiao,
            isMpKuaishou,
            isWhiteAppBar: false,
            isViewGiveup: false,
            isEdit:false,
            taskId:"",
            submitId:"",
            remarker:"",
            taskTitle:"",
            completeCount:0,
            repeateDes:"",
            subStatus:-1,
            stepList:[
            ]
            
        }
    },
    onLoad(options){
        let _self = this;
        let  taskId = options.taskId;
        let  submitId = options.submitId;
        if(taskId){
            this.setData({
                taskId:taskId
            })
           
        }
        if(submitId  && submitId != "undefined" ){
            this.setData({
                submitId:submitId
            })
           
        }
        function ready() {
            console.log('ready 是否是小程序::', window.__wxjs_environment === 'miniprogram');
            if (window.__wxjs_environment === 'miniprogram') {
                // 是小程序环境
                _self.isMpWeixinH5 = true;
            }
        }
        if (isH5) {
            setTimeout(() => {
                if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
                console.log('开始监听window.ev.WeixinJSBridgeReady');
                document.addEventListener('WeixinJSBridgeReady', ready, false)
                } else {
                ready()
                }
            }, 500)
        }
        this.getTaskDetail()
     },
    methods:{
        scrollEv(e) {
            console.log('scrollEv====')
            let scrollTop =  e.target.scrollTop
            if (typeof scrollTop === 'number') {
                if (scrollTop > 50) {
                // tabbar背景切换
                    this.isWhiteAppBar = true;
                } else {
                    this.isWhiteAppBar = false;
                }
            }
        },
        getTaskDetail(){
            let parms ={
                id:this.taskId
            }
            if(this.submitId){
                parms.submitId = this.submitId
            }
            queryTaskDetail(parms).then(res =>{
                if(res.code == 200){
                    let data = res.data

                    let remarker = data.remarker;
                    if (remarker.length) {
                        remarker = remarker.trim();
                    }
                    this.setData({
                        taskTitle:data.title,
                        remarker
                    })
                    if(data.subStatus == 3){
                        this.filterRejectItem(data.taskDetails, data.taskSubdetails)
                    }else{
                        this.filterItem(data.taskDetails)
                    }
                    
                    if(data.submitId){
                        this.setData({
                            submitId:data.submitId
                        })
                    }
                    if(data.subStatus == 0 || data.subStatus == 3){
                        this.setData({
                            isEdit:true
                        })
                    }
                    this.dealCheckBtn(data.subStatus)
                    this.dealRepeateDes(data)
                    console.log("queryTaskDetail====")
   
                }
            })
        },
        filterItem(stepList){
           if(stepList && stepList.length > 0){
                for(let i =0 ;i< stepList.length;i++){
                    let item = stepList[i]
                    item.upLoadImg=""
                }
                this.setData({
                    stepList:stepList
                })
            }
        },
        filterRejectItem(stepList,subItemList){
           if(stepList && stepList.length > 0){
                for(let i =0 ;i< stepList.length;i++){
                    let item = stepList[i]
                    item.upLoadImg=""
                    if(subItemList && subItemList.length > 0){
                        for(let j =0 ;j< subItemList.length;j++){
                            let subItem = subItemList[j]
                            if(item.id == subItem.id){
                                if(item.dtype == 5){
                                    item.upLoadImg = subItem.picUrl
                                }else if(item.dtype == 6){
                                    item.value=subItem.value
                                }
                            }
                        }
                    }
                }
                    
                this.setData({
                    stepList:stepList
                })
            }
        },
        
        dealRepeateDes(item){
            //设备类型（1 andriod 2ios 0 不限）
            let deviceType= item.deviceType
            let repeateDes = "完成数："+item.completeCount
            if(deviceType == 1){
              repeateDes +=  " | 仅支持设备：安卓" 
            }else if(deviceType == 2){
                repeateDes +=  " | 仅支持设备：苹果" 
            }
            //做单模式 0每人1次 2每人多次(repeateTime默认3) 1每日一次
            let repeated =item.repeated
            //重复做单次数
            let repeateTimes = item.repeateTimes
            if (repeated == 1) {
                if ( repeateTimes == 0) {
                    repeateDes +=  " | 每天1次，不限天数" 
                } else {
                    repeateDes +=  " | 每天1次，每天1次，连续"+repeateTimes+"天" 
                }
            } else if (repeated == 2) {
                if (repeateTimes == 99) {
                    repeateDes +=  " | 不限次数，不限天数" 
                 } else {
                    repeateDes +=  " | 可做"+ repeateTimes+ "次，不限时间"       
                }
            } else if (repeated == 3) {
                 repeateDes +=  " | 每日"+ repeateTimes+ "次，不限时间"     
            }  
            this.setData({
                repeateDes
            })
        },
        //subStatus //任务提交状态 -1未认领 0已认领 1已提交 2审核通过 3驳回 100:报名过期 101 放弃
        dealCheckBtn(subStatus){
            this.setData({
                subStatus
            })
          
        },
        getBtnText(){
            let btnStr = '' 
            if(this.subStatus == 100){
                btnStr = "已过期"
            }else if (this.subStatus == 2){
                btnStr = "已完成"
            }else if (this.subStatus == 1){
                btnStr = "审核中"
            }
            return btnStr
        },
        toGiveUp() {
            this.isViewGiveup = true;
        },
        saveGiveUp(){
            let parms ={
                id:this.submitId
            }
            giveUpTask(parms).then(res =>{
               if(res.code == 200){
                    this.$showToast("放弃成功")
                    uni.navigateBack({
                        delta: 1
                    });
                 return
               }
            })
        },
        applyTask(){
            let parms ={
                taskId:this.taskId
            }
            taskApply(parms).then(res =>{
                if(res.code == 200){
                    this.$showToast("报名成功")
                    this.setData({
                        submitId:res.data.submitId,
                        subStatus:0,
                        isEdit:true,
                    })
                }

            }) 
        },
        dealCommitTask(){
            let parms ={
                submitId:this.submitId,
            }
            let commitList =[]
            for(let i = 0; i< this.stepList.length;i++){
                let item = this.stepList[i]
                 if(item.dtype == 5 ){
                    if(item.upLoadImg){
                        console.log("upLoadImg===>"+item.upLoadImg)
                        let imgItem ={
                            dtype:item.dtype,
                            picUrl:item.upLoadImg,
                            detailId:item.id,
                            findex:item.findex
                        }
                        commitList.push(imgItem)
                    }else{
                       
                        this.$showToast("第" + (i + 1) + "步需要提交截图或提交失败重新选图片")
                        return
                    
                    }
                 }else if( item.dtype == 6 ){
                    if(item.value){
                        console.log("upLoadImg==value=>"+item.value)
                        let txtItem ={
                            dtype:item.dtype,
                            value:item.value,
                            detailId:item.id,
                            findex:item.findex
                        }
                        commitList.push(txtItem)
                    }else{
                        this.$showToast("第" + (i + 1) + "步骤需提交信息")  
                        return
                    }
                 }
            }
            parms.subdetails =commitList
            submitTask(parms).then(res =>{
                if(res.code == 200){
                    this.$showToast("提交成功")
                    this.setData({
                        subStatus:1,
                        isEdit: false
                    })
                }
            })
            console.log("paee===="+ JSON.stringify(commitList))
        },
        qrCodeScan(imgUrl) {
            native.qrCodeScan(imgUrl)
        },
        saveImg(imageUrl){
            if (isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
                saveAlbum(imageUrl)
                return
            } else if (this.isMpWeixinH5) {
                let path = `/pages/webview/transfer?action=downloadImage&picUrl=${imageUrl}`; 
                console.log('page>> ', path);
                wx.miniProgram.navigateTo({
                    url: path
                })
                return;
            }
            native.saveImg(imageUrl)
        },
        copyTxt(content){
            if (isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou || this.isMpWeixinH5) {
                copy(content)
                return
            }
            native.copyText(content)
        },
        openLink(linkUrl){
            native.GotoWithOpenURL(linkUrl)
        },
        selUpImg(position,item){
            console.log("选图片")
            if (isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
                pickAndUploadImage((img) => {
                    item.upLoadImg = img
                    this.stepList[position] = item
                    this.setData({
                        stepList: this.stepList
                    })
                })
                return;
            } else if (isH5 && window.wx) {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album'],
                    success: function(res) {
                        // 预览图片
                        console.log('res>>> ', res)
                        uploadExec(res.tempFiles[0]).then((url) => {
                            console.log('上传url>>> ', url)
                            item.upLoadImg = url;
                            this.stepList[position] = item
                            this.setData({
                                stepList: this.stepList
                            })
                        })
                    }
                });
                return;
            }
            // let url = "https://img.taomile.cn/sw/mch_undefined_1697097379857.jpeg"
            native.pickImgToUpload(data =>{
                console.log("url ===>"+JSON.stringify(data))
                item.upLoadImg = data.data
                this.stepList[position] = item
                this.setData({
                    stepList: this.stepList
                })
                console.log("fffffff==="+JSON.stringify(item))
                console.log("fffffff==to="+JSON.stringify(this.stepList))
            })
        },
        cleanImg(position,item){
            item.upLoadImg = ""
            this.stepList[position] = item
            this.setData({
               stepList: this.stepList
           })
        },
        previewImg(imgUrl){
            if (isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
                uni.previewImage({
                    urls: [imgUrl]
                })
                return;
            }
           let previewList = [{
            id: parseInt(Math.random() * 10000) + '',
            isTop: 0,
            isPic: 1,
            url: imgUrl
            }]
            setPreviewData(previewList)
            this.$navigateTo('/pages/welfare/preview')
         }
    }
 }
 </script> 
<style lang="scss">
.index-page {
    width: 100%;
    height: 100%;
    background-color: #fff;
 
    
    .box-1 {
      position: relative;
      margin-bottom: 16rpx;
      background: linear-gradient(180deg,#f50,#F9EEE7);
      padding-bottom: 160rpx;
      height: 100%;
    }
    .text-2{
        color: #7B828E;
        font-size: 24rpx;
        margin-top: 16rpx;
    }
    .fg-white{
        background-color: #fff;
        border-radius: 32rpx;
        box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(77,14,0,0.2);
        margin: 0rpx 32rpx 32rpx 32rpx;
    }
    .text-bold{
        color: #1C1C1E;
        font-weight: bold;
        font-size: 32rpx;
    }

    .box-type{
        padding: 32rpx; 
        display: flex;
        align-items: center;
        .img-type{
            height: 104rpx;
            width: 104rpx;
            min-width: 104rpx;
        }
    }
    .step-box{
       margin: 32rpx 0 0 0;
       display: flex;
       .text-number{
            min-width: 40rpx;
            height: 40rpx;
            line-height: 40rpx;
            padding: 0 14rpx;
            color: #fff;
            font-size: 24rpx;
            text-align: center;
            background-color: #F96A35;
            border-radius: 20rpx;
       }
       .step-ly{
          margin-left: 16rpx;
          overflow:hidden;
          width: 100%;
          .step-title{
            color: #1A1B1E;
            font-size: 28rpx;
            word-wrap: break-word;
            word-break: break-all;
          }
          .text-invite{
             height: 64rpx;
             flex: 1;
             border: 2rpx solid #D9DCE0;
             line-height: 64rpx;
             border-radius: 16rpx;
             word-wrap: break-word;
             word-break: break-all;
             overflow: hidden;
             white-space: nowrap;
             padding: 0 26rpx;
             margin-right: 16rpx;
             display: inline-block;
             
          }
          .dark-btn{
            min-width: 168rpx;
            height: 64rpx;
            line-height: 64rpx;
            font-size: 24rpx;
            color: #fff;
            text-align: center;
            font-weight: bold;
            background-color: #F65352;
            border-radius: 32rpx;
            padding: 0 24rpx;
            margin-right: 24rpx;
          }
          .img-qcode{
             width: 50%;
             margin-top: 24rpx;
          }
          .img-des{
             width: 50%;
          }
          .img-check{
             width: 100%;
          }
          .text-img-des{
             background: rgba(0, 0, 0, 0.8);
             width: 96rpx;
             text-align: center;
             height: 36rpx;
             font-size: 24rpx;
             border-radius: 0rpx 12rpx 0rpx 12rpx;
             color: #fff;
             position: absolute;
             top: 0rpx;
             z-index: 99;
          }
          .text-input-tip{
             height: 64rpx;
             width: 100%;
             line-height: 64rpx;
             color: #D9DCE0;
             font-size: 28rpx;
             border-radius: 16rpx;
             border: 2rpx solid #D9DCE0;
             padding-left: 26rpx;
          }
          .input-item{
                width:  100%;
                height: 64rpx;
                align-items: center;
                padding: 0 26rpx;
                border: 2rpx solid #D9DCE0;
                border-radius: 16rpx;
                .input-value{
                    color: #1A1B1E;
                    font-size: 32rpx;
                    height: 100%;
                }   
           }
       }
    }
    .pg-bottom{
        position:fixed;
        bottom: 0;
        background: white;
        height: 160rpx;
        display: flex;
        width: 100%;
        justify-content: center;
        padding: 20rpx 40rpx;
        .btn-light{
            height: 72rpx;
            flex:1;
            font-size: 28rpx;
            font-weight: bold;
            text-align: center;
            color: #F65352;
            background: rgba(246,83,82,0.24);
            line-height: 72rpx;
            border-radius: 36rpx;
            margin-right: 32rpx;

        }
        .btn{
            background-color: #F65352;
            border-radius: 36rpx;
            color: #fff;
            font-size: 28rpx;
            font-weight: bold;
            text-align: center;
            height: 72rpx;
            width: 60%;
            line-height: 72rpx;
            &.disable{
                background-color: #CCCCCC;

            }
        }
    }
}
</style>  